import { isArray, isEmpty, Obj } from 'esy-ui';
import { makeAutoObservable } from 'mobx';
import { createContext, useContext } from 'react';

/** OtherState 类中的全局变量 */
export type OtherStateType = 'collets';

export class OtherState {
  constructor() {
    makeAutoObservable(this);
    this.updataCollets = this.updataCollets.bind(this);
    this.isCollet = this.isCollet.bind(this);
  }

  // 收藏游戏Id
  collets: Map<number, Obj> = new Map();

  // 收藏的游戏是否发生了变化
  colletCount: number = 1;

  // 更新状态
  updataCollets(list?: Obj[]) {
    this.collets.clear();
    if (isArray(list) && !isEmpty(list)) {
      for (let i = 0; i < list.length; i++) {
        this.collets.set(list[i].Gid, list[i]);
      }
    } else {
      // 没有就清空
      this.collets.clear();
    }
    this.colletCount = list?.length || 0;
  }

  // 判断当前游戏是否已收藏
  isCollet(gId: number, cls?: Map<number, Obj>) {
    if (cls?.size > 0) {
      return cls.has(gId);
    }
    return this.collets.has(gId);
  }
}

// 利用createContext 创建storeContext
export const storeOther = createContext(new OtherState());

// 导出一个hook 获取全局state的变量值
export const useOtherStore = () => useContext(storeOther);
